package com.ncloud.web;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ncloud.common.exception.UserException;

@RestController
@RequestMapping("/api")
public class OpenNCloudWeb {
	private final static Logger logger = LoggerFactory.getLogger(OpenNCloudWeb.class);
	@RequestMapping
	public Object openNCloud(String service, String method, HttpServletRequest request, HttpServletResponse response){
		JSONObject params = new JSONObject();
		Object info = null;
		try {
			int length = request.getContentLength();
			if (length > 0) {
				byte [] b = new byte[length];
				request.getInputStream().read(b);
				params = JSONObject.parseObject(new String(b));
				
			}
			Object userID = request.getAttribute("userID");
			if (userID != null)
				params.put("userID", userID);

			ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
			Object obj = ac.getBean(service);
			Method m = obj.getClass().getMethod(method, JSONObject.class);
			logger.info("调用方法{}"+m.getName());
			logger.info("调用参数{}"+params.toJSONString());
			info = m.invoke(obj, params);
		} catch (BeansException | NoSuchMethodException | SecurityException | IllegalAccessException
				| IllegalArgumentException | InvocationTargetException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Throwable throwable = getErrorMessage(e);
			String mess = throwable.getMessage();
			int s = mess.indexOf(":");
			int es = mess.indexOf(System.getProperty("line.separator"));
			String mesString = mess.substring(s+2, es);
			JSONObject result = new JSONObject();
			result.put("code", "8888");
			result.put("message", mesString);
			return result;
		}
		JSONObject result = new JSONObject();
		result.put("code", "0000");
		result.put("message", "OK!");
		result.put("info", info);
		return JSON.parseObject(JSON.toJSONString(result,SerializerFeature.WriteMapNullValue));
	}
	
	public static Throwable getErrorMessage(Throwable throwable){
		if(throwable instanceof UserException) return throwable;
		Throwable inner = throwable.getCause();
		Throwable temp = null;
		if(inner != null){
			temp = getErrorMessage(inner);
		}else{
			return throwable;
		}
		return temp;
	}

}
